package part2.task2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Producer implements Runnable {
    private final Buffer<Object> buffer;
    private final String name;
    private final ReentrantLock lock;
    private final Condition addCondition;
    private final Condition getCondition;


    public Producer(String name,ReentrantLock lock,Condition addCondition,Condition getCondition, Buffer<Object> buffer) {
        this.buffer = buffer;
        this.name=name;
        this.lock=lock;
        this.addCondition=addCondition;
        this.getCondition=getCondition;
    }

    @Override
    public void run() {
        Object product=null;
        while (!Thread.currentThread().isInterrupted()) {
            if (product==null)
                product=new Object();
            try {
                lock.lock();
                if (buffer.add(product)){
                    product=null;
                    getCondition.signal();
                    System.out.println("Producer "+name+" add.");
                } else {
                    try {
                        System.out.println("Producer "+name+" wait.");
                        addCondition.await();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            } finally {
                lock.unlock();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
